<template>
    <zt-dialog v-model="visible" :title="titleName" @confirm="confirmBtn" :loading="isLoading" :showFooter="true"
        :showFullScreen="false" width="700px" height="500px" :showConfirm="true">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm" status-icon>
            <el-form-item label="按钮名称" prop="name">
                <el-input v-model.trim="ruleForm.name" placeholder="请输入按钮名称" />
            </el-form-item>
            <el-form-item label="按钮标识" prop="serial">
                <el-input v-model.trim="ruleForm.serial" placeholder="请输入按钮标识(标识不能与其他的重复，推荐使用父级标识为前缀)">
                    <template #prepend>
                        <el-select v-model="ruleForm.serial" placeholder="快捷选择" style="width: 100px">
                            <el-option :label="item.label" :value="item.value" v-for="item in serialOptions" />
                        </el-select>
                    </template>
                    <template #append>
                        <el-popconfirm :title="'是否使用父级标识' + props.objectValue.serial + '为前缀'" @confirm="popconfirmChange">
                            <template #reference>
                                <el-button :icon="WarningFilled"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>

                </el-input>
            </el-form-item>
            <el-form-item label="排序" prop="seq">
                <el-input v-model.number="ruleForm.seq" placeholder="请输入排序" />
            </el-form-item>
        </el-form>
    </zt-dialog>
</template>

<script setup>
import {
    WarningFilled,
} from '@element-plus/icons-vue'
import ztDialog from '@/components/zt-dialog/index.vue'
import { ElMessage, ElNotification } from 'element-plus'
import { apiPostCreateMenu, apiPutUpdateMenu } from "@/api/admin/menuManage/api.js"

const isLoading = ref(false)

const emit = defineEmits(['success', 'update:modelValue'])
const props = defineProps({
    // 当前类型
    currentType: {
        type: String,
        default: 'add'
    },
    // 控制弹窗显示
    visible: {
        type: Boolean,
        default: false
    },
    // 传递过来的值
    objectValue: {
        type: Object,
        default: () => {
            return {}
        }
    }
})

const ruleFormRef = ref(null)
const ruleForm = reactive({
    name: '',//按钮,
    catalogId: '',//分类id (代码 1:web,2:app)
    type: 'button',//	资源类型(代码 none:栏目/menu:菜单/iframe:框架/button:按钮/href:链接/dashboard:面板/plugin:插件/authority:权限),可用值:authority,button,dashboard,href,iframe,menu,none,plugin
    seq: 0,//排序
    serial: '',//按钮编号
})

const updateForm = reactive({
    menuId: '',//菜单id
})

const rules = reactive({
    name: [
        { required: true, message: '请输入按钮名称', trigger: 'blur' },
    ],
    serial: [
        { required: true, message: '请输入按钮标识', trigger: 'blur' },
    ],
    seq: [
        { required: true, message: '请输入排序', trigger: 'blur' },
    ],
})

// 动态获取标题
const titleName = computed(() => {
    return props.currentType == 'edit' ? '修改按钮' : '添加按钮'
})

// 子组件定义自己的visible
const visible = computed({
    get: () => props.visible,
    set: (value) => {
        // 清除表单字段值
        Object.keys(ruleForm).forEach(key => {
            switch (key) {
                case 'seq':
                    ruleForm[key] = 0
                    break;
                case 'type':
                    ruleForm[key] = 'button'
                    break;
                default:
                    ruleForm[key] = '';
                    break;
            }
        });
        ruleFormRef.value.clearValidate()
        emit('update:modelValue', value)
    },
})
const serialOptions = ref([])
// 监听当前currentType
watch(() => props.currentType, (e) => {
    if (e === 'add') {
        serialOptions.value = [
            {
                label: '新增',
                value: props.objectValue.serial + '_create',
            },
            {
                label: '修改',
                value: props.objectValue.serial + '_modify',
            },
            {
                label: '详情',
                value: props.objectValue.serial + '_detail',
            },
            {
                label: '删除',
                value: props.objectValue.serial + '_delete',
            },
        ]
    }
    if (e === 'edit') {
        serialOptions.value = [
            {
                label: '新增',
                value: props.objectValue.serial.split('_')[0] + '_create',
            },
            {
                label: '修改',
                value: props.objectValue.serial.split('_')[0] + '_modify',
            },
            {
                label: '详情',
                value: props.objectValue.serial.split('_')[0] + '_detail',
            },
            {
                label: '删除',
                value: props.objectValue.serial.split('_')[0] + '_delete',
            },
        ]
    }
}, {
    deep: true,
    immediate: true
})

// 监听传递过来的值 赋值
watch(() => props.objectValue, (e) => {
    if (e) {
        if (props.currentType != 'add') {
            // 遍历 key 相等的赋值 
            Object.keys(e).forEach(item => {
                Object.keys(ruleForm).forEach(ele => {
                    if (item == ele) {
                        ruleForm[ele] = e[item]
                    }
                });
            });
        } else {
            ruleForm.catalogId = e.catalogId
        }
        updateForm.menuId = e.menuId
    }
}, {
    deep: true,
    immediate: true
})

// 提示弹窗确认事件
function popconfirmChange() {
    ruleForm.serial = props.objectValue.serial + '_'
    ElNotification({
        title: '前缀添加成功',
        message: '父级前缀添加成功，请继续添加后缀标识',
        type: 'success',
        position: 'top-left',
    })
}
// 确认按钮
async function confirmBtn() {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            // 编辑时执行
            if (props.currentType == 'edit') {
                editChange()
                return false
            }
            addChange()//添加

        } else {
            const firstValue = Object.values(fields)[0];
            ElMessage({
                message: firstValue[0].message,
                type: 'warning',
            })
        }
    })
}

// 添加方法
function addChange() {
    isLoading.value = true
    apiPostCreateMenu({ ...ruleForm, parentId: props.objectValue.menuId }).then(res => {
        if (res.success) {
            ElMessage({
                message: '按钮添加成功',
                type: 'success',
            })
            emit('success')
            visible.value = false
            return false
        }
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }).finally(() => {
        isLoading.value = false
    })
}

// 编辑方法
function editChange() {
    isLoading.value = true
    apiPutUpdateMenu({ ...ruleForm, ...updateForm }).then(res => {
        if (res.success) {
            ElMessage({
                message: '按钮修改成功',
                type: 'success',
            })
            emit('success')
            visible.value = false
            return false
        }
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }).finally(() => {
        isLoading.value = false
    })
}


</script>

<style lang='scss' scoped></style>